﻿using BaseData.API.Read.Applications.HospitalInformation.Command;
using BaseData.API.Read.Dtos;
using BaseData.Domain.HospitalInformation;
using BaseData.ErrorCode;
using BaseData.Infrastructure.Interfaces;
using MediatR;

namespace BaseData.API.Read.Applications.HospitalInformation.CommandHandler
{
    public class DoctorShowCommandHandler:IRequestHandler<DoctorShowCommand,ApiResult<ApiPaging<DoctorDto>>>
    {
        IBaseRepository<Doctors> repositorydoctor;
        IBaseRepository<Departments> repositorydepartments;

        public DoctorShowCommandHandler(IBaseRepository<Doctors> repositorydoctor, IBaseRepository<Departments> repositorydepartments)
        {
            this.repositorydoctor = repositorydoctor;
            this.repositorydepartments = repositorydepartments;
        }

        public async Task<ApiResult<ApiPaging<DoctorDto>>> Handle(DoctorShowCommand request, CancellationToken cancellationToken)
        {
            var res = from a in repositorydoctor.GetAll()
                      join b in repositorydepartments.GetAll() on a.DepartmentId equals b.DepartmentId
                      where !a.Isdelete
                      select new DoctorDto()
                      {
                         DoctorId=a.DoctorId,
                        DoctorName=a.DoctorName,
                        DoctorPicture=a.DoctorPicture,
                        HospitalCampus=a.HospitalCampus,
                        ProfessionalTitle=a.ProfessionalTitle,
                        DoctorTag=a.DoctorTag,
                        registrationFee=a.registrationFee,
                        DiagnosticFee=a.DiagnosticFee,
                        DoctorIntroduce=a.DoctorIntroduce,
                        DoctorStatus=a.DoctorStatus,
                        Isdelete=a.Isdelete,
                        DepartmentId=b.DepartmentId,
                        DepartmentName=b.DepartmentName,
                      };
            if(!string.IsNullOrEmpty(request.DoctorName))
            {
                res = res.Where(x => x.DoctorName.Contains(request.DoctorName));
            }
            if(request.DepartmentId!=null)
            {
                res = res.Where(x => x.DepartmentId==(request.DepartmentId));
            }
            int TotalCount = res.Count();
            int PageCount = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            res = res.OrderBy(x => x.DepartmentId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            return new ApiResult<ApiPaging<DoctorDto>>()
            {
                Message = ApiEnum.查询成功.ToString(),
                Code = ApiEnum.查询成功,
                Data = new ApiPaging<DoctorDto>()
                {
                    TotalCount = TotalCount,
                    PageCount = PageCount,
                    Data = res.ToList()
                }
            };


        }
    }
}
